<?php

namespace backend\controllers;

use yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use backend\models\service\TweetService as Tweet;
use backend\behaviors\TweetBehavior;
use backend\models\service\NovelService as Novel;
use backend\models\service\Chapter;
use backend\models\odm\TitleOdm as Title;
use backend\models\UploadForm;

class TweetController extends Controller {

    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    '*'             => ['get'],
                    'del-images'    => ['post'],
                    'images'        => ['post','get'],
                    'create'    => ['post'],
                    'del'    => ['get','post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Lists all Company models.
     * @return mixed
     */
    public function actionIndex() {
//        if(!Yii::$app->authManager->checkAccess(Yii::$app->user->id,'novel.index')){
//            return $this->redirect('/site/index');
//        }
        $model = new Tweet;
        $model->attachBehavior('tweet', new TweetBehavior);
        
        $admin = new \backend\models\Admin();
        $cooperation = $admin->getAdmins(array('type'=>2));
        $channel = $admin->getAdmins(array('type'=>3));
        $params = Yii::$app->request->queryParams;
        return $this->render('index', [
            'searchModel' => $model,
            'dataProvider' => $model->list_for_index(),
            'select' => $params,
            'cooperation' => $cooperation,
            'channel' => $channel,
        ]);
    }
    
    /**
     * 图片库
     */
    public function actionImages()
    {
        $upload = new UploadForm();
        $get = Yii::$app->request->get();
        $params = array(
            'page'      => isset( $get['page'] ) && intval($get['page']) ? intval($get['page']) : 1,
            'pageSize'  => 10,
        );
        $model = new \backend\models\Imgs();
        $data = $model->getImageList($params);
        $data['model'] = $upload;
        $data['params'] = $params;
        return $this->render('images',$data);
    }
    
    /**
     * 删除图片
     */
    public function actionDelImages()
    {
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $model = new \backend\models\Imgs();
            $res = $model->delImages($post['ids']);
            if($res){
                echo "成功";
            }else{
                echo "失败";
            }
        }
    }
    
    /**
     * 编辑推文
     */
    public function actionUpdate()
    {
        $get = \Yii::$app->request->get();
        $id = $get['id'];
        $act = isset($get['act']) ? $get['act'] : 'tweet';
        $data['info'] = \backend\models\Tweet::getById($id);
        $data['title_list'] = \backend\models\service\TitleService::getAll();
        $data['pic_list'] = \backend\models\Imgs::getAllImage();
        $data['act'] = $act;
        return $this->render('update',$data);
    }
    

    /**
     * 
     */
    public function actionCreate()
    {
        if(\Yii::$app->request->isPost){
            $post = \Yii::$app->request->post();
            $model = \backend\models\Tweet::findOne(['id'=>$post['id']]);
            $model->title_id = $post['title_id'];
            $model->img_url = $post['img_url'];
            $model->status = 1;
            if($model->save()){
                $id = $post['id'];
                $data['info'] = \backend\models\Tweet::getById($id);
                //生成预览模板
                $basePath = yii\helpers\Url::to('@app');
                $dir_path = $basePath.'/web/tpl/'.$data['info']['channel_name'].'/html/';
                if(!file_exists($dir_path)){
                    mkdir($dir_path,0755,true);
                }
                $model = new Chapter();
                $novel = new Novel();
                $info = $novel->getNovelInfo($data['info']['novel_id']);
                $cinfo = $model->getChaptersInfo($data['info']['chapter_id']);
                $url = "http://59.110.0.207:9604/".$info['novel_pinyin']."/".$info['novel_title']."/".$cinfo['chapter_name'].".txt";
                $content = '';
                if(@fopen($url,'r')){
                    $content = file_get_contents($url);
                    $content = iconv("gb2312", "utf-8//IGNORE",$content);
                }
                $title = new Title();
                $title_info = $title->getTitleInfo($data['info']['title_id']);
                $detail_path = $basePath.'/web/tpl/'.$data['info']['channel_name'].'/html/'.$id.'.html';
                $fp = fopen($basePath."/web/tpl.html","r"); 
                $str = fread($fp,filesize($basePath."/web/tpl.html")); 
//                $detail_path = 'F:/novel_admin/backend/web/tpl/'.$data['info']['channel_name'].'/html/'.$id.'.html';
//                $fp = fopen("F:/novel_admin/backend/web/tpl.html","r"); 
//                $str = fread($fp,filesize("F:/novel_admin/backend/web/tpl.html")); 
                // $detail_path = '/usr/local/nginx/html/web_zhaixinwei/novel_admin/backend/web/tpl/'.$data['info']['channel_name'].'/html/'.$id.'.html';
                // $fp = fopen("/usr/local/nginx/html/web_zhaixinwei/novel_admin/backend/web/tpl.html","r"); 
                // $str = fread($fp,filesize("/usr/local/nginx/html/web_zhaixinwei/novel_admin/backend/web/tpl.html")); 
                $str = str_replace("{img_src}",$data['info']['img_url'],$str);
                $str = str_replace("{title}",$title_info['name'],$str);
                $str = str_replace("{content}",$content,$str);
                fclose($fp);
                if($handle = fopen($detail_path,"w")){
                    fwrite($handle,$str);   
                    fclose($handle);
                };
                echo json_encode(array('status'=>0,'msg'=>'修改成功'));
            }
        }
    }
    
    public function actionView($id){
        $url = 'http://test.xinwei.com:88/tpl/test2/html/'.$id.'.html';
        
    }
    
    /**
     * @param integer $id
     * @return mixed
     */
    public function actionDel($id) {
        $model = $this->findModel($id);
        if ($model->delete()) {
            return $this->redirect(['index']);
        }
    }
    
    protected function findModel($id) {
        if (($model = Tweet::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
     }
    
}
